package com.bookstore.servlet.admin;

import com.bookstore.entity.Product;
import com.bookstore.entity.User;
import com.bookstore.factory.ServiceFactory;
import com.bookstore.service.ProductService;
import com.bookstore.service.UserService;
import com.bookstore.servlet.BaseServlet;
import com.bookstore.utils.GudgeType;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;

@WebServlet("/admin/manager.do")
public class ManagerServlet extends BaseServlet {
    UserService userService = ServiceFactory.getUserService();
    ProductService productService = ServiceFactory.getProductService();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
        String password = req.getParameter("password");
        User user = userService.loginMeneger(username, password);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (user == null) {
            resp.sendRedirect("/admin/login.html");
        } else {
            req.getSession().setAttribute("admin",user);
            resp.sendRedirect("/admin/index.jsp");
        }
    }

    protected void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String gender = req.getParameter("gender");
        String email = req.getParameter("email");
        String telephone = req.getParameter("telephone");
        String introduce = req.getParameter("introduce");
        String activeCode = req.getParameter("activeCode");
        User user = new User(null, username, "123456", gender, email, telephone, introduce, activeCode, 1, 0, new Timestamp(System.currentTimeMillis()));
        System.out.println(user);
        int register = userService.register(user);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (register <= 0) {
            writer.write(new Gson().toJson("0"));
        } else {
            writer.write(new Gson().toJson("1"));
        }
    }

    protected void queryAllUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        List<User> users = userService.showAllUser();
        PrintWriter writer = resp.getWriter();
        if (users == null || users.size() <= 0) {
            req.setAttribute("users", "users为空");
        } else {
            req.setAttribute("users", users);
        }
        req.getRequestDispatcher("/admin/user_list.jsp").forward(req, resp);
    }

    protected void deleteuser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String id = req.getParameter("id");
        int result = userService.deleteUser(Long.parseLong(id));
        PrintWriter writer = resp.getWriter();
        if (result <= 0) {
            writer.write("删除错误");
        } else {
            resp.sendRedirect("./manager.do?action=queryAllUser");
        }
    }

    protected void updateuser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String id = req.getParameter("id");
        if (GudgeType.isNull(id)) {
            writer.write("重置错误");
            return;
        }
        User user = userService.queryUserById(Long.parseLong(id));
        if (user == null) {
            writer.write("重置错误");
            return;
        }
        user.setPassword("123456");
        int i = userService.resetPwd(user);
        if (i > 0) {
            resp.sendRedirect("./manager.do?action=queryAllUser");
        }
    }

//    protected void queryAllProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setContentType("text/html;charset=utf-8");
//        List<Product> products = productService.queryAllProduct();
//        PrintWriter writer = resp.getWriter();
//        req.getSession().setAttribute("products", products);
//        req.getRequestDispatcher("/admin/product_list.jsp").forward(req, resp);
//    }

    protected void deleteProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String id = req.getParameter("id");
        int result = productService.deleteProduct(Integer.parseInt(id));
        PrintWriter writer = resp.getWriter();
        if (result <= 0) {
            writer.write("删除错误");
        } else {
            resp.sendRedirect("./manager.do?action=queryAllProduct");
        }
    }

    protected void reBackProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String id = req.getParameter("id");
        Product product = productService.queryProductById(Integer.parseInt(id));
        PrintWriter writer = resp.getWriter();
        if (product == null) {
            return;
        }
        writer.write(new Gson().toJson(product));
    }

    protected void updateProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String productId = req.getParameter("id");
        String productName = req.getParameter("name");
        String productPrice = req.getParameter("price");
        String categary = req.getParameter("category");
        String productNum = req.getParameter("pnum");
        String productImg = req.getParameter("imgurl");
        String productDes = req.getParameter("description");
        Product product = new Product(Integer.parseInt(productId), productName, Double.parseDouble(productPrice), categary, Integer.parseInt(productNum), productImg, productDes);
        int result = productService.updateProduct(product);
        PrintWriter writer = resp.getWriter();
        if (result <= 0) {
            writer.write(new Gson().toJson("0"));
            return;
        }
        writer.write(new Gson().toJson("1"));
    }

    protected void addProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String productName = req.getParameter("name");
        String productPrice = req.getParameter("price");
        String categary = req.getParameter("category");
        String productNum = req.getParameter("pnum");
        String productImg = req.getParameter("imgurl");
        String productDes = req.getParameter("description");
        Product product = new Product(null, productName, Double.parseDouble(productPrice), categary, Integer.parseInt(productNum), productImg, productDes);
        int result = productService.insertProduct(product);
        PrintWriter writer = resp.getWriter();
        if (result <= 0) {
            writer.write(new Gson().toJson("0"));
            return;
        }
        writer.write(new Gson().toJson("1"));
    }

    protected void queryAllProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String maxNum = req.getParameter("maxnum");
        String limite = req.getParameter("start");
        List<Product> products=null;
        if (GudgeType.isNull(maxNum,limite)){
            products= productService.queryLimiteProduct(0,5);
            maxNum="5";
            limite="0";
        }else {
            products = productService.queryLimiteProduct(Integer.parseInt(limite),Integer.parseInt(maxNum));
        }
        int count = productService.queryProductCount();
        int index=(Integer.parseInt(limite)+Integer.parseInt(maxNum))/Integer.parseInt(maxNum);
        PrintWriter writer = resp.getWriter();
        if (products ==null||products.size()==0) {
            writer.write(new Gson().toJson("失败"));
        } else {
            req.getSession().setAttribute("products",products);
            req.getSession().setAttribute("productsCount",count);
            req.getSession().setAttribute("index",index);
            req.getRequestDispatcher("/admin/product_list.jsp").forward(req, resp);
        }
    }

    protected void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        resp.sendRedirect("./login.html");
    }

    protected void keepLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user =(User) req.getSession().getAttribute("admin");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (user==null){
            writer.write(new Gson().toJson("0"));
        }else {
            writer.write(new Gson().toJson(user));
        }
    }

}
